package com.handpay.zztong.hp.main.fragment;

import android.annotation.TargetApi;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ImageSpan;
import android.text.style.RelativeSizeSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.handpay.framework.ClientEngine;
import com.handpay.framework.SecureManager;
import com.handpay.framework.notice.ApiNoticeFactory;
import com.handpay.framework.notice.ApiNoticeListener;
import com.handpay.framework.utils.CommonUtils;
import com.handpay.zztong.hp.R;
import com.handpay.zztong.hp.accountcenter.activity.TransferCashLimitManagementActivity;
import com.handpay.zztong.hp.base.activity.ZZTongActivity;
import com.handpay.zztong.hp.base.callback.BusinessEngineListener;
import com.handpay.zztong.hp.base.fragment.BaseFragment;
import com.handpay.zztong.hp.bean.ActionBar;
import com.handpay.zztong.hp.bean.NoticeInfo;
import com.handpay.zztong.hp.config.ZZTConfig;
import com.handpay.zztong.hp.config.ZZTConstant;
import com.handpay.zztong.hp.db.ormlite.DataBaseModel;
import com.handpay.zztong.hp.log.HPLog;
import com.handpay.zztong.hp.main.activity.MainActivity;
import com.handpay.zztong.hp.main.model.FunctionInfo;
import com.handpay.zztong.hp.main.model.certexpiry.QueryCertNoExpiryDateBean;
import com.handpay.zztong.hp.main.model.certexpiry.QueryCertNoExpiryDateModel;
import com.handpay.zztong.hp.main.model.limit.LimitBean;
import com.handpay.zztong.hp.main.model.limit.LimitModel;
import com.handpay.zztong.hp.main.model.merchantinfo.MerchantInfo;
import com.handpay.zztong.hp.main.model.merchantinfo.MerchantInfoModel;
import com.handpay.zztong.hp.main.model.merchantswitch.MerchantSwitchBean;
import com.handpay.zztong.hp.main.model.merchantswitch.MerchantSwitchModel;
import com.handpay.zztong.hp.main.widget.icon.IconBaseAdapter;
import com.handpay.zztong.hp.main.widget.icon.IconBaseOnItemClickListener;
import com.handpay.zztong.hp.protocol.BaseProtocolKey;
import com.handpay.zztong.hp.setting.activity.SettingActivity;
import com.handpay.zztong.hp.utils.AccountUtils;
import com.handpay.zztong.hp.utils.AccountUtils.AccountStatus;
import com.handpay.zztong.hp.utils.StatusBarUtil;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;


@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class MyFragment extends BaseFragment implements ApiNoticeListener {
    private static final String TAG = "MyFragment";
    private TextView account, account_noupload;
    private TextView shopName;
    private TextView money_tv, tv_version;

    private double fmoney;
    private String dayLimit = null;
    private String monthLimit = null;
    private String debitCardLimit = null;
    private String creditCardLimit = null;
    private String dayTotalLimit = null;
    private String monthTotalLimit = null;
    private String icDebitCardLimit = null;
    private String icCreditCardLimit = null;
    private ArrayList<String> dataArray = null;
    public List<NoticeInfo> notices = null;
    public int count = 1;
    private LinearLayout no_upload_ll;
    private ImageButton upload_btn;
    private RelativeLayout account_info_rl;
    private int swiperMode = ZZTConstant.SWIPER_GOTO_SWIPER_SELECT;
    protected IconBaseAdapter mIconBaseAdapter;
    private QueryCertNoExpiryDateModel mQueryCertNoExpiryDateModel;
    private DataBaseModel dataBaseModel;
    private String userId;
    private ImageButton my_setting_btn;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (mQueryCertNoExpiryDateModel == null) {
            mQueryCertNoExpiryDateModel = new QueryCertNoExpiryDateModel();
        }
        dataArray = new ArrayList<String>();
        dataArray.add(FunctionInfo.MY_BASIC_INFO_CODE);
        dataArray.add(FunctionInfo.MY_QUALIFICATION_INFO_CODE);
        dataArray.add(FunctionInfo.MY_COLLECT_CARD_MANAGEMENT_CODE);
        dataArray.add(FunctionInfo.MY_COLLECT_LIMIT_CODE);
        dataArray.add(FunctionInfo.MY_COLLECT_FLOW_CODE);
        dataArray.add(FunctionInfo.MY_COLLECT_WITHDRAW_CODE);
        dataArray.add(FunctionInfo.MY_SWIPE_SELECT_CODE);
//        dataArray.add(FunctionInfo.MY_USER_NOTICE_CODE);
        dataArray.add(FunctionInfo.MY_T0_QUALIFICATION_CODE);
        notices = new ArrayList<NoticeInfo>();
        if (null == AccountUtils.getAccountT0Switch(mActivity) || AccountUtils.getAccountT0Switch(mActivity).equals("0")) {
            // 获取用户T0提现资质提交开关
            getMerchantSwitchData();
        }
        ApiNoticeFactory.getInstance().registerApiNoticeListener(this);
    }

    protected void getMerchantSwitchData() {
        Hashtable<String, String> params = new Hashtable<String, String>();
        params.put("account", SecureManager.getInstance().des(AccountUtils.getAccountName(mActivity), 1, null));
        params.put("clientChannel", ZZTConfig.UPDATE_CHANNEL);
        params.put("channel", ClientEngine.CHANNEL);
//        mainActivity.doJsonPost(mainActivity, ZZTongActivity.Do_getMerchantSwitch, MerchantSwitchBean.class, params);
        new MerchantSwitchModel().doMerchantSwitchPost(mainActivity, params, new BusinessEngineListener<MerchantSwitchBean>() {
            @Override
            public void callbackBusinessResponse(MerchantSwitchBean bean) {
                int isOpen = CommonUtils.objectToInt(bean.getIsOpen());
                if (isOpen != -1) {
                    isOpenT0switch = isOpen;
                }
                AccountUtils.setAccountT0Switch(mActivity, String.valueOf(isOpenT0switch));
                if (AccountUtils.getAccountT0Switch(mActivity) != null && AccountUtils.getAccountT0Switch(mActivity).equals("0")) {
                    if (dataArray.contains(FunctionInfo.MY_T0_QUALIFICATION_CODE)) {
                        dataArray.remove(FunctionInfo.MY_T0_QUALIFICATION_CODE);
                    }
                }
                mIconBaseAdapter.setData(dataArray);
            }
        });
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mViewGroup = (ViewGroup) inflater.inflate(R.layout.fragment_my, container, false);
        initView();
        StatusBarUtil.setTranslucentForImageViewInFragment(getActivity(), 0, null);
        return mViewGroup;
    }

    private void initView() {
        account = (TextView) mViewGroup.findViewById(R.id.account_tv);
        account_noupload = (TextView) mViewGroup.findViewById(R.id.account_noupload_tv);
        shopName = (TextView) mViewGroup.findViewById(R.id.textview_shopName);
        money_tv = (TextView) mViewGroup.findViewById(R.id.money_tv);
        GridView myGridView = (GridView) mViewGroup.findViewById(R.id.myGridView);
        no_upload_ll = (LinearLayout) mViewGroup.findViewById(R.id.no_upload_ll);
        account_info_rl = (RelativeLayout) mViewGroup.findViewById(R.id.account_info_rl);
        upload_btn = (ImageButton) mViewGroup.findViewById(R.id.upload_btn);
        tv_version = (TextView) mViewGroup.findViewById(R.id.tv_version);
        tv_version.setText(getString(R.string.tv_version) + ClientEngine.VERSION);
        mIconBaseAdapter = new IconBaseAdapter(mainActivity);
        dataBaseModel = DataBaseModel.getInstance(mainActivity);
        userId = AccountUtils.getUserId(mainActivity);
        mIconBaseAdapter.bShowNotice = dataBaseModel.isReadNotice(userId);
        myGridView.setAdapter(mIconBaseAdapter);
        mIconBaseAdapter.setData(dataArray);
        Initialization();
        upload_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                doZiZhiTiJiao();
            }
        });
        myGridView.setOnItemClickListener(new IconBaseOnItemClickListener(mainActivity));
        //初始化收款金额，放在抖动效果
        SpannableString msp = new SpannableString("0.00");
//        msp.setSpan(new RelativeSizeSpan(2.0f), 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        money_tv.setText(msp);
        my_setting_btn = (ImageButton) mViewGroup.findViewById(R.id.my_setting_btn);
        my_setting_btn.setOnClickListener(CommonUtils.createNoQuickResponseViewListener(ZZTConstant.NO_RESPONSE_CLICK_TIME, new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mainActivity, SettingActivity.class);
                mainActivity.startActivity(intent);
            }
        }));
        TextView rt = (TextView) mViewGroup.findViewById(R.id.tv_state_onupload);
        Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.icon_my_warn);
        ImageSpan imgSpan = new ImageSpan(getActivity(), b, ImageSpan.ALIGN_BASELINE);
        SpannableString spanString = new SpannableString("icon_new");
        spanString.setSpan(imgSpan, 0, 8, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        rt.setText(spanString);
        rt.append(" " + getActivity().getString(R.string.QualificationsPromptTip));
    }

    /***
     * 显示上传资料
     *
     * @param hiddenOrdisplay
     */
    private void HiddenOrDisplayNoupLoad(boolean hiddenOrdisplay) {
        if (hiddenOrdisplay) {
            no_upload_ll.setVisibility(View.VISIBLE);
            account_info_rl.setVisibility(View.INVISIBLE);
        } else {
            no_upload_ll.setVisibility(View.INVISIBLE);
            account_info_rl.setVisibility(View.VISIBLE);
        }
    }

    /***
     * 设置状态
     *
     * @param accountStatus
     * @param queryLimit    设置完后，是否查询限额信息？
     */
    private void SettingState(AccountStatus accountStatus, boolean queryLimit) {
        if (accountStatus.equals(AccountStatus.NOUPLOAD)) {
            HiddenOrDisplayNoupLoad(true);
        } else {
            HiddenOrDisplayNoupLoad(false);
            if (queryLimit) {
                doGetLimit();
            }
        }
    }

    /***
     * 初始化界面数据
     */
    private void Initialization() {
        if (AccountUtils.getAccountName(mActivity) != null) {
            account.setText("Hi," + AccountUtils.getAccountName(mActivity));
            account_noupload.setText("Hi," + AccountUtils.getAccountName(mActivity));
        }
        if (AccountUtils.getShopName(mActivity) != null && AccountUtils.getAccountStatus(mActivity) != AccountStatus.NOUPLOAD) {
            shopName.setText(AccountUtils.getShopName(mActivity));
        }
//        doGetNotices();
        if (AccountUtils.getAccountStatus(mActivity) != null) {
            SettingState(AccountUtils.getAccountStatus(mActivity), true);
        }
        if (AccountUtils.getAccountStatus(mActivity) == AccountStatus.SUCCESS) {
//            HPLog.i("result", "flag_certNoExpiryDate:" + flag_certNoExpiryDate);
//            if (mCertNoExpiryDate == -1) {//这情况说明应用还没请求过接口
                queryCardExpiryDate();
//            }
// else if (flag_certNoExpiryDate == -1) {//请求过了跟据值判断功能是否显示
//                if (dataArray.contains(FunctionInfo.FUNCTIONID[20])) {
//                    dataArray.remove(FunctionInfo.FUNCTIONID[20]);
//                }
//            }


        }
    }

    /**
     * 获取证件信息是否过期
     */
    private void queryCardExpiryDate() {
        if (!checkMyActivityIsNull()) {
            Hashtable<String, String> params = new Hashtable<>();
            params.put("account", SecureManager.getInstance().des(AccountUtils.getAccountName(mActivity), 1, null));
            mQueryCertNoExpiryDateModel.doQueryCertNoExpiryDatePost(mainActivity, params, new BusinessEngineListener<QueryCertNoExpiryDateBean>() {
                @Override
                public void callbackBusinessResponse(QueryCertNoExpiryDateBean bean) {
                    String status = bean.getStatus();
                    int  mCertNoExpiryDate = (!TextUtils.isEmpty(status)) ? Integer.valueOf(status) : -1;
                    mIconBaseAdapter.bShowCertExpiryDate = mCertNoExpiryDate == 3;
                    if (status.equals("-1") || status.equals("00")) {
                        if (dataArray.contains(FunctionInfo.MY_ID_Cardate_CODE)) {
                            HPLog.d(HPLog.SSX_TAG,"remove idcard");
                            dataArray.remove(FunctionInfo.MY_ID_Cardate_CODE);
                            mIconBaseAdapter.setData(dataArray);
                        }
                    } else {
                        if (!dataArray.contains(FunctionInfo.MY_ID_Cardate_CODE)) {
                            HPLog.d(HPLog.SSX_TAG,"add idcard");
                            dataArray.add(FunctionInfo.MY_ID_Cardate_CODE);//身份证补件
                            mIconBaseAdapter.setData(dataArray);
                        }
                    }
                }
            });
        }
    }


    /***
     * 交易限额查询
     */
    private void doGetLimit() {
        if (AccountUtils.getAccountPhone(mActivity) == null) {
            return;
        }
        Hashtable<String, String> params = new Hashtable<String, String>();
        params.put(BaseProtocolKey.PHONE, SecureManager.getInstance().des(AccountUtils.getAccountPhone(mActivity), 1, null));
        params.put(BaseProtocolKey.ACCOUNT, SecureManager.getInstance().des(AccountUtils.getAccountName(mActivity), 1, null));
        params.put(BaseProtocolKey.CHANNEL, ClientEngine.CHANNEL);
        params.put(BaseProtocolKey.KEY_APPCODE, BaseProtocolKey.APPCODE_TRANSFER);
        new LimitModel().doLimitPost(mainActivity, params, new BusinessEngineListener<LimitBean>() {
            @Override
            public void callbackBusinessResponse(LimitBean bean) {
                String dayTraffic = bean.getDayTraffic();
                if (dayTraffic != null) {
                    fmoney = (double) Long.parseLong(dayTraffic) / 100;
                    String displayMoney = String.format("%1$.2f", fmoney);
                    ClientEngine.getInstance().saveGlobal("dayTraffic", fmoney);
                    //设置小数点前面的数字，是小数点后面的两倍大小
                    SpannableString msp = new SpannableString(displayMoney);
//                    msp.setSpan(new RelativeSizeSpan(2.0f), 0, displayMoney.length() - 3, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                    money_tv.setText(msp);
                    // money_tv.setText("" + CommonUtils.formatMoney(fmoney));
                }
                dayTotalLimit = bean.getDayLimit();
                monthTotalLimit = bean.getMonthLimit();
                debitCardLimit = bean.getDebitCardLimit();
                creditCardLimit = bean.getCreditCardLimit();
                dayLimit = bean.getDayMagLimit();
                monthLimit = bean.getMonthMagLimit();
                icDebitCardLimit = bean.getIcDebitCardLimit();
                icCreditCardLimit = bean.getIcCreditCardLimit();
                // 保存提现权限;
                String wdPermission = bean.getWdPermission();
                if (null != wdPermission) {
                    AccountUtils.setWDPermission(mActivity, wdPermission);
                }
                mainActivity.closeProgressDialog();
                if (AccountStatus.CHECKING.equals(AccountUtils.getAccountStatus(mActivity))) {
                    getMerchantInfo();
                }
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
//		HPLog.i(HPLog.YL_TAG,"onRantesume 1:");
//		if (null == AccountUtils.getAccountT0Switch() || AccountUtils.getAccountT0Switch().equals("0") ) {
//			// 获取用户T0提现资质提交开关
//			getMerchantSwitchData();
//		}
//		HPLog.i(HPLog.YL_TAG,"onResume 2:");
        if (!MainActivity.isReceivablesFragment) {
            MainActivity.currFragTag = ZZTConstant.FRAGMENT_FLAG_MY;
        } else {
            MainActivity.isReceivablesFragment = false;
        }
//		HPLog.i(HPLog.YL_TAG,"onResume 3:"+ZZTongActivity.isUploadComposeSusses);
        if (ZZTongActivity.isUploadComposeSusses) {
            SettingState(AccountUtils.getAccountStatus(mActivity), true);
            ZZTongActivity.isUploadComposeSusses = false;
        }
    }

    private void getMerchantInfo() {
        Hashtable<String, String> params = new Hashtable<String, String>();
        params.put(BaseProtocolKey.ACCOUNT, SecureManager.getInstance().des(AccountUtils.getAccountName(mActivity), 1, null));
        params.put(BaseProtocolKey.CHANNEL, ClientEngine.CHANNEL);
        params.put(BaseProtocolKey.NEWBANKFLAG, ZZTongActivity.newBankFlag);
//        mainActivity.doJsonPost(mainActivity, ZZTongActivity.DO_zztGetMerchantInfo, MerchantInfo.class, params);
        new MerchantInfoModel().doMerchantInfoPost(mainActivity, params, new BusinessEngineListener<MerchantInfo>() {
            @Override
            public void callbackBusinessResponse(MerchantInfo bean) {
                String statusStr = bean.getStatus();
                String failDes = bean.getFailDescpriction();
                AccountUtils.setAccountStatus(mActivity, AccountUtils.convertStatus(statusStr));
                AccountUtils.setAccountFailDes(mActivity, failDes);
                SettingState(AccountUtils.getAccountStatus(mActivity), false);
            }
        });
    }


    @Override
    public String getFragmetTitle() {
        return ZZTConstant.FRAGMENT_FLAG_MY;
    }

    @Override
    public ActionBar getFragmentActionBar() {
        super.getFragmentActionBar();
        ImageView setting_iv = new ImageView(mActivity);
        setting_iv.setImageResource(R.drawable.my_setting);
        setting_iv.setPadding(0, 0, 30, 0);
        setting_iv.setOnClickListener(CommonUtils.createNoQuickResponseViewListener(ZZTConstant.NO_RESPONSE_CLICK_TIME, new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mainActivity, SettingActivity.class);
                mainActivity.startActivity(intent);
            }
        }));
        return new ActionBar(getFragmetTitle(), setting_iv);
    }

    @Override
    public void doShouKuanXianE() {
        if (dayLimit != null && dayLimit.trim().length() > 0 && monthLimit != null && monthLimit.trim().length() > 0 && debitCardLimit != null && debitCardLimit.trim().length() > 0 && creditCardLimit != null && creditCardLimit.trim().length() > 0 && dayTotalLimit != null && dayTotalLimit.trim().length() > 0 && monthTotalLimit != null && monthTotalLimit.trim().length() > 0 && icDebitCardLimit != null && icDebitCardLimit.trim().length() > 0 && icCreditCardLimit != null && icCreditCardLimit.trim().length() > 0) {
            Intent intent = new Intent(mainActivity, TransferCashLimitManagementActivity.class);
            intent.putExtra("dayLimit", dayLimit.equals("-1") ? this.getString(R.string.Unlimited) : CommonUtils.formatMoney(Double.parseDouble(dayLimit) / 100));
            intent.putExtra("monthLimit", monthLimit.equals("-1") ? this.getString(R.string.Unlimited) : CommonUtils.formatMoney(Double.parseDouble(monthLimit) / 100));
            intent.putExtra("debitCardLimit", debitCardLimit.equals("-1") ? this.getString(R.string.Unlimited) : CommonUtils.formatMoney(Double.parseDouble(debitCardLimit) / 100));
            intent.putExtra("creditCardLimit", creditCardLimit.equals("-1") ? this.getString(R.string.Unlimited) : CommonUtils.formatMoney(Double.parseDouble(creditCardLimit) / 100));
            intent.putExtra("dayTotalLimit", dayTotalLimit.equals("-1") ? this.getString(R.string.Unlimited) : CommonUtils.formatMoney(Double.parseDouble(dayTotalLimit) / 100));
            intent.putExtra("monthTotalLimit", monthTotalLimit.equals("-1") ? this.getString(R.string.Unlimited) : CommonUtils.formatMoney(Double.parseDouble(monthTotalLimit) / 100));
            intent.putExtra("icDebitCardLimit", icDebitCardLimit.equals("-1") ? this.getString(R.string.Unlimited) : CommonUtils.formatMoney(Double.parseDouble(icDebitCardLimit) / 100));
            intent.putExtra("icCreditCardLimit", icCreditCardLimit.equals("-1") ? this.getString(R.string.Unlimited) : CommonUtils.formatMoney(Double.parseDouble(icCreditCardLimit) / 100));
            this.startActivity(intent);
        }
    }


    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
//        mNoticeDB.close();
        Log.i("result", "--myfragment---onDestroy");
        ApiNoticeFactory.getInstance().unregisterApiNoticeListener(this);
    }

    @Override
    public void onVPOS() {
        super.onVPOS();
        HPLog.i(HPLog.FDL_TAG, "MyFragment onVPOS");
        switch (swiperMode) {
            case ZZTConstant.SWIPER_GOTO_SWIPER_SELECT:
//                swiperSelect(Intent intent1);
                break;
            case ZZTConstant.SWIPER_GOTO_ZIZHITIJIAO:
                doZiZhiTiJiao();
                break;
            default:
                break;
        }
    }

    public void doZiZhiTiJiao() {
        swiperMode = ZZTConstant.SWIPER_GOTO_ZIZHITIJIAO;
        if (mainActivity.checkSwiperOk(mainActivity, true)) {
            startActivity(mainActivity.getComposeIntent());
        }
    }

//    @Override
//    public void swiperConnect(Intent intent1) {
//        HPLog.i(HPLog.FDL_TAG, "MyFragment swiperConnect");
//        super.swiperConnect(intent1);
//        swiperMode = ZZTConstant.SWIPER_GOTO_SWIPER_SELECT;
//    }

    public void swiperSelect(Intent intent1) {
        swiperMode = ZZTConstant.SWIPER_GOTO_SWIPER_SELECT;
        mainActivity.startActivityForResult(intent1, ZZTConstant.CONNECT_SWIPER_CODE);
    }

    @Override
    public void onNotifyNotice(int action, Bundle bundle) {
        if (mIconBaseAdapter != null) {
            mainActivity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
//                    NoticeDataHelper mNoticeDB = new NoticeDataHelper(mActivity);
                    mIconBaseAdapter.bShowNotice = dataBaseModel.isReadNotice(userId);
                    mIconBaseAdapter.notifyDataSetChanged();
//                    mNoticeDB.close();
                }
            });
        }
    }

    @Override
    public int[] getNoticeAction() {
        int actions[] = {NOTICE_ACTION};
        return actions;
    }
}
